package com.woniuxy.sddfp.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniuxy.sddfp.common.exception.Assert;
import com.woniuxy.sddfp.common.model.dto.user.UserRegisterDto;
import com.woniuxy.sddfp.common.result.enums.impl.BusinessCode;
import com.woniuxy.sddfp.system.entity.User;
import com.woniuxy.sddfp.system.entity.UserDetail;
import com.woniuxy.sddfp.system.mapper.UserMapper;
import com.woniuxy.sddfp.system.service.IUserDetailService;
import com.woniuxy.sddfp.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yellow doctor
 * @since 2025-05-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    IUserDetailService UserDetailService;

    /**
     * 1、判断手机号是否已注册
     * 2、添加user对象
     * 3、添加userDetail对象
     *
     * @param userRegisterDto
     */
    @Transactional
    @Override
    public void regist(UserRegisterDto userRegisterDto) {
        // 判断手机号是否已注册
        User user = getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getPhone, userRegisterDto.getPhone()));


        Assert.error(!Objects.isNull(user), BusinessCode.USER_EXISTED);

        // 添加user对象
        User user1 = new User();
        user1.setUserName(userRegisterDto.getUserName());
        user1.setPhone(userRegisterDto.getPhone());
        user1.setPwd(userRegisterDto.getPwd());
        user1.setUserType("1");
        save(user1);


        // 添加userDetail对象
        UserDetail userDetail = new UserDetail();
        userDetail.setId(user1.getId());
        userDetail.setUserName(userRegisterDto.getUserName());
        userDetail.setPhone(userRegisterDto.getPhone());
        userDetail.setBorrowMoney(new BigDecimal(0));
        // 用户码 随机数
        userDetail.setUserCode("UC_"+ UUID.randomUUID().toString().substring(0,12));
        // 请求码
        userDetail.setUserCode("");
        // 银行卡绑定状态
        userDetail.setCardBindStatus(false);
        UserDetailService.save(userDetail);


    }
}
